import pymysql
import pandas as pd


def Aconnect(localhost,username,password,database):
    # 打开数据库连接
    db = pymysql.connect(localhost, username, password, database)
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    return cursor,db

def Afetchall(localhost,username,password,database,sql):
    cursor,db=Aconnect(localhost,username,password,database)
    try:
        pd_data = pd.read_sql(sql, db)
        cursor.execute(sql)
        data=cursor.fetchall()
        db.commit()
    except:
        db.rollback()
    db.close()
    return data,pd_data

def Acreatetalbes(localhost,username,password,database,sql):
    cursor, db = Aconnect(localhost, username, password, database)
    cursor.execute(sql)
    db.commit()
    db.close()
    return print('创建数据库表成功')

def Ainsert(localhost,username,password,database,sql):
    cursor, db = Aconnect(localhost, username, password, database)
    try:
        cursor.execute(sql)
        db.commit()
    except:
        print('出现错误')
        db.rollbacg()
    cursor.close()
    db.close()
    return print('插入数据成功')

